package com.wey.springboot.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wey.springboot.bean.QuartzTask;
import com.wey.springboot.mapper.QuartzTaskMapper;
import com.wey.springboot.task.MessageRemindTask;
import lombok.extern.log4j.Log4j2;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Log4j2
public class MessageRemindService extends ServiceImpl<QuartzTaskMapper, QuartzTask> {
  private final String groupName = "短信提醒";
  @Autowired
  private Scheduler scheduler;
  @Autowired
  private QuartzTaskMapper mapper;

  // 程序启动开始加载定时任务
  public void loadTask() {
    List<QuartzTask> quartzTasks = mapper.selectList(
        Wrappers.<QuartzTask>lambdaQuery()
            .eq(QuartzTask::getGroupName, groupName)
            .eq(QuartzTask::getStatus, 1));
    if (quartzTasks == null || quartzTasks.size() == 0) {
      log.warn(groupName + "-定时任务组加载数据为空");
      return;
    }
    for (QuartzTask quartzTask : quartzTasks) {
      try {
        start(quartzTask);
        log.info("{}-{}-定时任务加载成功", groupName, quartzTask.getName());
      } catch (Exception e) {
        log.error("{}-{}-定时任务加载失败", groupName, quartzTask.getName());
      }
    }
  }

  // 启动任务
  public void startTask(Integer id) throws SchedulerException {
    LambdaUpdateWrapper<QuartzTask> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
    lambdaUpdateWrapper.eq(QuartzTask::getId, id).set(QuartzTask::getStatus, 1);
    mapper.update(null, lambdaUpdateWrapper);
    QuartzTask quartzTask = mapper.selectById(id);
    start(quartzTask);
  }

  // 停止任务
  public void stopTask(Integer id) throws SchedulerException {
    LambdaUpdateWrapper<QuartzTask> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
    lambdaUpdateWrapper.eq(QuartzTask::getId, id).set(QuartzTask::getStatus, 0);
    mapper.update(null, lambdaUpdateWrapper);
    scheduler.deleteJob(JobKey.jobKey(id.toString(), groupName));
    log.info("{}-{}-定时任务删除成功", groupName, id);
  }

  // 删除任务
  public void deleteTask(Integer id) throws SchedulerException {
    mapper.deleteById(id);
    scheduler.deleteJob(JobKey.jobKey(id.toString(), groupName));
    log.info("{}-{}-定时任务删除成功", groupName, id);
  }

  //更新任务
  public void updateTask(QuartzTask quartzTask) throws SchedulerException {
    mapper.updateById(quartzTask);
    scheduler.deleteJob(JobKey.jobKey(quartzTask.getId().toString(), groupName));
    if (quartzTask.getStatus() == 1) {
      start(quartzTask);
    }
  }

  // 组装任务并启动
  private void start(QuartzTask quartzTask) throws SchedulerException {
    CronTrigger cronTrigger = getCronTrigger(quartzTask);
    JobDetail jobDetail = getJobDetail(quartzTask);
    scheduler.scheduleJob(jobDetail, cronTrigger);
    log.info("{}-{}-定时任务启动成功", groupName, quartzTask.getName());
  }

  //组装JobDetail
  private JobDetail getJobDetail(QuartzTask quartzTask) {
    return JobBuilder.newJob()
        .withIdentity(JobKey.jobKey(quartzTask.getId().toString(), groupName))
        .withDescription(quartzTask.getDescription())
        .ofType(MessageRemindTask.class).build();
  }

  //组装CronTrigger
  private CronTrigger getCronTrigger(QuartzTask quartzTask) {
    CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTask.getCron());
    return TriggerBuilder.newTrigger()
        .withIdentity(TriggerKey.triggerKey(quartzTask.getId().toString(), groupName))
        .withSchedule(cronScheduleBuilder)
        .build();
  }
}
